package com.xuecheng.manage_cms_client.mq;

import com.alibaba.fastjson.JSON;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.manage_cms_client.service.PageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component // 把普通pojo实例化到spring容器中，相当于配置文件中的<bean id="" class=""/>
public class ConsumerPostPage {
    /**
     * ConsumerPostPage作为发布页面的消费客户端，监听
     * 页面发布队列的消息，收到消息后从mongodb下载文件，保存在本地。
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerPostPage.class);
    private PageService pageService;

    @Autowired
    public ConsumerPostPage(PageService pageService){
        this.pageService = pageService;
    }

    @RabbitListener(queues = {"${xuecheng.mq.queue}"})
    public void postPage(String msg){
        // 解析消息
        Map map = JSON.parseObject(msg, Map.class);
        LOGGER.info("receive cms post page:{}", msg.toString());
        // 取出页面的id
        String pageId = (String)map.get("pageId");
        // 校验页面是否合法
        CmsPage cmsPage = pageService.findCmsPageById(pageId);
        if(cmsPage == null){
            LOGGER.error("receive postpage msg, cmsPage is null, pageId:{}", pageId);
            return;
        }
        // 将页面从GridFs中下载到服务器
        pageService.savePageToServerPath(pageId);
    }
}
